package com.website.main.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.website.common.vo.Tree;
import com.website.main.service.S_Admin;
import com.website.main.util.Utils;
import com.website.mybatis.dao.PowerDao;
import com.website.mybatis.entity.SysPower;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class S_AdminImpl implements S_Admin {

    @Autowired
    PowerDao dao;

    @Override
    public List<Tree> getAllMenuList() {
        SysPower s = new SysPower();
        s.setLeaf(false);
        return Utils.powerTOTreeMenu(dao.selectList(new QueryWrapper<>(s)));
    }

    @Override
    public List<Tree> getAllMenuList(Collection<SysPower> sysPowers) {
        SysPower s = new SysPower();
        s.setLeaf(false);
        return Utils.powerTOTreeMenu(delEmp(dao.selectList(new QueryWrapper<>(s)), sysPowers));
    }

    private List<SysPower> delEmp(List<SysPower> l, Collection<SysPower> sysPowers) {
        List<SysPower> tmp = new ArrayList<>();
        for (SysPower p : sysPowers) {
            if(Boolean.FALSE.equals(p.getLeaf())){
                if(tmp.contains(p)) {
                    continue;
                }
                tmp.add(p);
            }
            if(p.getParentId() != null){
                addParent(l, p.getParentId(), tmp);
            }
        }
        return tmp;
    }

    private void addParent(List<SysPower> all, Integer parentId, List<SysPower> result){
        for(SysPower s: all){
            if(s.getId().equals(parentId)){
                if(!result.contains(s)){
                    result.add(s);
                    if(s.getParentId() == null) {
                        return;
                    }
                }
                if(s.getParentId() != null){
                    addParent(all, s.getParentId(), result);
                }
            }
        }
    }

}
